<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UploadsController extends Controller
{
    public function uploadImg(Request $request)
    {
        $file = $request->file("mypic");
        $data = [];
        // dd($file);
        if (!empty($file)) {
            foreach ($file as $key => $value) {
                $len = $key;
            }
            if ($len > 25) {
                return response()->json(['errno' => 6, 'info' => '最多可以上传25张图片']);
            }
            for ($i = 0; $i <= $len; $i++) {
                // $n 表示第几张图片
                $n = $i + 1;
                if ($file[$i]->isValid()) {
                    if (in_array(strtolower($file[$i]->extension()), ['jpeg', 'jpg', 'gif', 'gpeg', 'png'])) {
                        $picname = $file[$i]->getClientOriginalName(); //获取上传原文件名
                        $ext = $file[$i]->getClientOriginalExtension(); //获取上传文件的后缀名
                        // 重命名
                        $filename = time() . str_random(6) . "." . $ext;
                        if ($file[$i]->move("uploads/images", $filename)) {
                            $newFileName = config('app.url') . '/' . "uploads/images" . '/' . $filename;
                            // return response()->json(['errno' => 0, 'info' => '上传成功', 'newFileName' => $newFileName ]);
                            $data[] = $newFileName;
                            // return response()->json(['errno' => 0, 'data' => [$newFileName]]);

                        } else {
                            return response()->json(['errno' => 4, 'info' => '上传失败']);
                        }
                        // $return[] = ['errno' => 0, 'info' => $msg, 'newFileName' => $newFileName];
                    } else {
                        return response()->json(['errno' => 3, 'info' => '第' . $n . '张图片后缀名不合法!<br/>' . '只支持jpeg/jpg/png/gif格式']);
                    }
                } else {
                    return response()->json(['errno' => 1, 'info' => '第' . $n . '张图片超过最大限制!<br/>' . '图片最大支持2M']);
                }
            }

        } else {
            return response()->json(['errno' => 5, 'info' => '请选择文件']);
        }
        return response()->json(['errno' => 0, 'data' => $data]);

    }

    public function uploadFile(Request $request)
    {
        $file = $request->file("file");
        $pre = request()->input('pre', 'file');
        //保存图片
        if ($file) {
            $disk = \Storage::disk('qiniu');

            $path = $disk->put($pre, $file);
            if (config('app.debug')) {
                $url = $disk->url(['path' => $path, 'domainType' => 'default']);
            } else {
                $url = $disk->url(['path' => $path, 'domainType' => 'https']);
            }

            return response()->json(['recode' => 1, 'msg' => '上傳成功', 'info' => ['path' => $path, 'url' => $url]]);
        }
        return response()->json(['recode' => 0, 'msg' => '沒有圖片']);
    }
}
